package com.qf.filter;

import com.qf.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;

import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/*
 *@Description: 鉴权过滤器
 *@author:刘哥
 *@Date:86180 2022/10/26 20:20
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        获取请求对象
        ServerHttpRequest request = exchange.getRequest();
//        获取响应对象
        ServerHttpResponse response = exchange.getResponse();
//        获取用户访问的url路径
        String path = request.getURI().getPath();
//        判断如果是登录路径,注册路径退出路径放行
        if(path.contains("/auth/login")){
            return chain.filter(exchange);
        }
//        从cookie里面获取jwt令牌
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie token = cookies.getFirst("token");
//        判断如果jwt令牌不存在,抛出401权限不足异常
        if (token==null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        解析jwt令牌
        String jwt = token.getValue();

        try {
//            解析jwt
            Claims claims = JwtUtil.parseJWT(jwt);
//          解析无问题后放入请求头中方便其他微服务远程调用时携带
            request.mutate().header("authorization","jwt");
            //        如果解析没问题,南无放行
            return chain.filter(exchange);
        } catch (Exception e) {
            //        解析异常说明那么jwt超市,妖魔有人篡改我伪造,抛出401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
